package client;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Panel;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.ListIterator;

import server.Cijferlijst;

/**
 * 
 * @author Jesse Gorter
 *
 */
public class MyListCard extends Panel 
{	
	GridBagLayout gbl = new GridBagLayout();
	MyList list;
	Cijferlijst cijferl;
	MyObserver observer;
	ArrayList<String[]> cijferlist;
	MyApplet applet;
	public MyListCard(Cijferlijst cijferlijst, MyApplet ap)
	{	
		this.applet = ap;
		cijferl = cijferlijst;
		this.setBackground(new Color(204, 255, 255));
		Insets insets = new Insets(0, 10, 10,0);
		this.setLayout(gbl);
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.insets = insets;
		gbc.gridx = 0; gbc.gridy= 0;
		
		try{
			MyObserver obexport = new MyObserverImpl(this);
			observer = (MyObserver) UnicastRemoteObject.exportObject(obexport,0);
			cijferl.addMyObserver(observer);
		}catch (RemoteException re){
			System.out.println("\nMyApplet - Observer maken gefaald!!!");
			re.printStackTrace();
		}
		
		list = new MyList(applet);
		this.getCijferlijst();
		list.setPreferredSize(new Dimension(400,300));
		this.add(list);
	}
	
	
	public void getCijferlijst()
	{	
		try
		{	
			list.removeAll();
			cijferlist = cijferl.selectAll();
			System.out.println(cijferlist);
			for(ListIterator<String[]> i = cijferlist.listIterator(); i.hasNext();)
			{
				String[] dataString = (String[])i.next();
				int stringcount = dataString[0].length();
				int spaces = list.nspaces() - stringcount;
				String spacestring = "";
				for(int j = 0; j<spaces; j++)
				{
					spacestring+= " ";
				}
				list.add(dataString[0] + spacestring + dataString[1]);
				
			}
		}
		catch(RemoteException re)
		{
			System.out.println("Exception bij update\nMyListCard - getCijferlijst()");
		}
		applet.repaint();
	}
	
	public void text()
	{
		
	}
	public void validate()
	{
		
	}
	public void delete()
	{
		try
		{
			int a = list.getSelectedIndex();
			String[] student = (String[])cijferlist.get(a);
			cijferl.delete(student[0]);
		}
		catch(RemoteException re)
		{
			
		}
	}
	public void update()
	{	
		int a = list.getSelectedIndex();
		String[] student = (String[])cijferlist.get(a);
		try
		{
			cijferl.update(student[0], applet.south.f1.getText(), applet.south.f2.getText());
		}catch(RemoteException re)
		{
			
		}
	}
	public void insert()
	{
		try
		{
			cijferl.insert(applet.south.f3.getText(), applet.south.f4.getText());
		}catch(RemoteException re)
		{
			
		}
	}
	public void deleteObserver(){
		try{
			cijferl.deleteMyObserver(observer);
		}catch (RemoteException re){}
	}
}
